package validation

import (
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"gopkg.in/go-playground/validator.v9"
	zh_translations "gopkg.in/go-playground/validator.v9/translations/zh"
	"reflect"
)

type ICustomValidator interface {
	Validate(interface{}) []string
}

//封装验证器
type BaseValidator struct {
	MyValidtor *validator.Validate
	trans      ut.Translator
}

func NewValidator() ICustomValidator {
	valid := &BaseValidator{}
	valid.initValidator()
	return valid
}

func (oValid *BaseValidator) initValidator() {
	//生成验证器的相关组件
	zh_ch := zh.New()                         //生成中文翻译器
	uni := ut.New(zh_ch)                      //将中文翻译器加入翻译器驱动模块中
	oValid.trans, _ = uni.GetTranslator("zh") //取出带中文翻译器的驱动
	oValid.MyValidtor = validator.New()       //生成验证器
	//验证器注册翻译器
	zh_translations.RegisterDefaultTranslations(oValid.MyValidtor, oValid.trans) //将验证器和翻译器绑定在一起
}


//验证结构体
func (oValid *BaseValidator) Validate(userIns interface{}) []string {
	valueIns := reflect.ValueOf(userIns)
	if valueIns.Kind() != reflect.Ptr && valueIns.Elem().Kind() != reflect.Struct {
		panic("传入参数必须是结构体指针")
	}

	err := oValid.MyValidtor.Struct(userIns)
	sliceError := make([]string, 0)
	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			//翻译错误信息
			return append(sliceError, err.Translate(oValid.trans))
		}
	}
	return sliceError
}
